<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>BHUDY - 角色管理</title>
    <script src="/res/js/bhudy.js"></script>
    <script src="/res/layui/layui.js"></script>
    <style>
        #tree ul {
            margin-left: 20px;
        }
    </style>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <div class="layui-col-xs12">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="roleName" lay-verify="roleName" autocomplete="off" placeholder="请输入名称"
                               class="layui-input">
                    </div>
                    <div class="layui-inline">
                        <button type="submit" class="layui-btn layui-btn-normal" lay-submit="" lay-filter="search">搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="javascript:location.reload();">刷新</button>
                    </div>
                </div>
            </form>
            <table id="tableDataList" class="layui-table" lay-filter="tableDataList"
                   lay-data="{url:'/api/v1/sysRoles', page:true, id:'tableDataList',toolbar:'default', defaultToolbar:['filter', 'exports', 'print']}">
                <thead>
                <tr>
                    <th lay-data="{type:'checkbox', fixed: 'left'}"></th>
                    <th lay-data="{field:'roleId', width:80, sort: true, fixed: 'left'}">roleId</th>
                    <th lay-data="{field: 'roleName', width:150}">roleName</th>
                    <th lay-data="{field: 'roleSign', width:150}">roleSign</th>
                    <th lay-data="{field: 'status', width:150}">status</th>
                    <th lay-data="{field: 'remark', width:150}">remark</th>
                    <th lay-data="{field: 'updateDate', width:150}">updateDate</th>
                    <th lay-data="{field: 'updateBy', width:150}">updateBy</th>
                    <th lay-data="{field: 'createDate', width:150}">createDate</th>
                    <th lay-data="{field: 'createBy', width:150}">createBy</th>
                    <th lay-data="{fixed: 'right', width:178, align:'center', toolbar: '#barDemo'}"></th>
                </tr>
                </thead>
            </table>

            <script type="text/html" id="barDemo">
                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event=" ">配置</a>
                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            </script>
        </div>
    </div>
</div>
</body>
<script>
    layui.use(['table', 'form', 'layedit', 'laydate'], function () {
        var table = layui.table,
            form = layui.form,
            layer = layui.layer,
            element = layui.element,
            $ = layui.jquery,
            url = "/api/v1/sysRole",
            superRoleId = 0;

        //监听头工具栏事件
        table.on('toolbar(tableDataList)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id),
                dataList = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    showUpdateOrCreate();
                    break;
                case 'update':
                    if (dataList.length === 0) {
                        layer.msg('请选择一行');
                    } else if (dataList.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        showUpdateOrCreate(dataList[0]);
                    }
                    break;
                case 'delete':
                    if (dataList.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        var roleIds = [];
                        dataList.forEach(data => {
                            roleIds.push(data.roleId);
                        });
                        //layer.alert('删除 [id]：' + userIds);
                        delFun(roleIds);
                    }
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(tableDataList)', function (obj) {
            var data = obj.data;
            console.log(obj.data)
            if (obj.event === 'del') {
                delFun([data.userId]);
            } else if (obj.event === 'edit') {
                showUpdateOrCreate(data);
            } else if (obj.event === 'configure') {
                configure(obj.data.roleId);
            }
        });

        // 搜索框
        form.on('submit(search)', function (data) {
            table.reload("tableDataList", {
                where: data.field,
                page: {curr: 1}//重新从第 1 页开始
            });
            return false;
        });

        // 修改或者添加方法
        form.on('submit(updateOrCreateBtn)', function (data) {
            if (data.field.roleId) {
                $.ajaxJsonPUT(url, JSON.stringify(data.field), function (resultData) {
                    resultFun(resultData);
                })
            } else {
                $.ajaxJsonPOST(url, JSON.stringify(data.field), function (resultData) {
                    resultFun(resultData);
                })
            }
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        // 删除方法
        function delFun(ids) {
            layer.confirm('真的删除行么', function (index) {
                $.ajaxJsonDEL(url + "s", JSON.stringify(ids), function (resultData) {
                    layer.msg(resultData.message);
                    setTimeout(function () {
                        layer.closeAll();
                        table.reload("tableDataList", {
                            where: null,
                            page: {curr: 1}//重新从第 1 页开始
                        });
                    }, 2000);
                });
            });
        }

        // 拿到后台返回结果做处理
        function resultFun(resultData) {
            layer.msg(resultData.message);
            if (resultData.code === 0) {
                setTimeout(function () {
                    layer.closeAll();
                    table.reload("tableDataList", {
                        where: null,
                        page: {curr: 1}//重新从第 1 页开始
                    });
                }, 2000);
            }
        }

        // 显示修改或者添加弹出窗口
        function showUpdateOrCreate(data) {
            //页面层-自定义
            let index = layer.open({
                type: 1,
                title: '操作窗口',
                closeBtn: 1,
                skin: 'layui-layer-lan',
                maxmin: true,
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    $("#updateOrCreateBtn").click();
                    return false;
                },
                content: `<form class="layui-form" style="margin: 10px 50px;" action="" lay-filter="updateOrCreateForm">
                            <input type="hidden" name="roleId" lay-verify="userId" autocomplete="off" class="layui-input">
                            <div class="layui-form-item">
                                <label class="layui-form-label">roleName</label>
                                <div class="layui-input-block">
                                    <input type="text" name="roleName" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">roleSign</label>
                                <div class="layui-input-block">
                                    <input type="text" name="roleSign" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">status</label>
                                <div class="layui-input-block">
                                    <input type="text" name="status" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">remark</label>
                                <div class="layui-input-block">
                                    <input type="text" name="remark" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <button type="submit" style="display: none;" id="updateOrCreateBtn" class="layui-btn layui-btn-normal" lay-submit="" lay-filter="updateOrCreateBtn"></button>
                        </form>`
            });
            layer.full(index);
            // 绑定数据
            form.val('updateOrCreateForm', data);
        }


        function configure(roleId) {
            superRoleId = roleId;
            $.getJSON("/api/v1/sysRoleMenus", `roleId=${roleId}`, function (resultData) {
                var content = `<form id="tree" class="layui-form layui-form-pane" action=""><ul>`;
                $.each(resultData.data, function (i, obj) {
                    content += `<li style="border: 1px solid #e6e6e6; margin: 10px; padding: 10px;"><div class="layui-form-item" pane>
                        <label class="layui-form-label">${obj.name}</label>
                        <div class="layui-input-block role-menu" data-id="${obj.id}">
                          <input type="checkbox" name="get" title="get" ${obj.get ? "checked" : ""}>
                          <input type="checkbox" name="post" title="post" ${obj.post ? "checked" : ""}>
                          <input type="checkbox" name="put" title="put" ${obj.put ? "checked" : ""}>
                          <input type="checkbox" name="delete" title="delete" ${obj.delete ? "checked" : ""}>
                          <input type="checkbox" name="all" title="all" ${obj.get && obj.post && obj.put && obj.delete ? "checked" : ""}>
                        </div>
                      </div>`;
                    //这里是添加所有的子菜单
                    content += loadchild(obj);
                });

                content += `</li></ul>
                    <button type="submit" style="display: none;" id="configureBtn" class="layui-btn layui-btn-normal" lay-submit="" lay-filter="configureBtn"></button>
                </form>`;
                let index = layer.open({
                    type: 1,
                    title: '操作窗口',
                    closeBtn: 1,
                    skin: 'layui-layer-lan',
                    maxmin: true,
                    btn: ['提交', '取消'],
                    yes: function (index, layero) {
                        $("#configureBtn").click();
                        return false;
                    },
                    content: content
                });

                form.render();
                layer.full(index);
            });
        }

        //组装子菜单的方法
        function loadchild(obj) {
            if (obj == null) {
                return '';
            }

            var content = '';
            if (obj.childrenMenuList != null && obj.childrenMenuList.length > 0) {
                content += '<ul>';
            } else {
                content += '<ul>';
            }

            if (obj.childrenMenuList != null && obj.childrenMenuList.length > 0) {
                $.each(obj.childrenMenuList, function (i, note) {
                    content += `<li><div class="layui-form-item" pane>
                        <label class="layui-form-label">${note.name}</label>
                        <div class="layui-input-block role-menu" data-id="${note.id}">
                          <input type="checkbox" name="get" title="get" ${note.get ? "checked" : ""}>
                          <input type="checkbox" name="post" title="post" ${note.post ? "checked" : ""}>
                          <input type="checkbox" name="put" title="put" ${note.put ? "checked" : ""}>
                          <input type="checkbox" name="delete" title="delete" ${note.delete ? "checked" : ""}>
                          <input type="checkbox" name="all" title="all" ${note.get && note.post && note.put && note.delete ? "checked" : ""}>
                        </div>
                      </div>`;
                    if (note.childrenMenuList == null) {
                        return;
                    }
                    content += loadchild(note);
                    content += `</li>`;
                });

                content += '</ul>';
            }
            return content;
        }

        // 修改或者添加方法
        form.on('submit(configureBtn)', function (data) {
            let menuList = [];
            for (let i = 0; i < $(".role-menu").length; i++) {
                let menu = {
                    "roleId": superRoleId,
                    "menuId": $(`.role-menu:eq(${i})`).data("id"),
                    "get": ($(`.role-menu:eq(${i})>input[name="get"]`).prop('checked') ? 1 : 0 ),
                    "post": ($(`.role-menu:eq(${i})>input[name="post"]`).prop('checked') ? 1 : 0 ),
                    "put": ($(`.role-menu:eq(${i})>input[name="put"]`).prop('checked') ? 1 : 0 ),
                    "delete": ($(`.role-menu:eq(${i})>input[name="delete"]`).prop('checked') ? 1 : 0 )
                };
                if (menu.get !== 0 || menu.post !== 0 || menu.put !== 0 || menu.delete !== 0) {
                    menuList.push(menu)
                }
            }

            $.ajaxJsonPOST(`/api/v1/sysRoleMenus?roleId=${superRoleId}`, JSON.stringify(menuList), function (resultData) {
                resultFun(resultData);
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

    });
</script>
</html>